<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>crontab 调度</title>
    <script src="./vue/vue.js"></script>
    <script src="./vue/vue-resource.min.js"></script>
    <!-- 引入样式 -->

    <link rel="stylesheet" href="./vue/index.css">
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

    <!-- 引入组件库 -->
    <script src="./vue/index.js"></script>
</head>
<body>

<div class="container-fluid" id="vueApp" v-cloak>
    <!-- 页头 -->
    <div class="row">
        <div class="col-md-12">
            <div class="page-header">
                <h1>管理后台<small>Crontab</small></h1>
            </div>
        </div>
    </div>

    <!-- 功能按钮 -->
    <div class="row">
        <div class="col-md-12">
            <button type="button" class="btn btn-primary" @click='edit({name:""})'>新建任务</button>
            <br/><br/>
            <br/>
            <ul class="list-group">
                <li class="list-group-item">worker节点</li>
                <li class="list-group-item" v-for="item in workers">{item}</li>
            </ul>
        </div>
    </div>

    <!-- 任务列表 -->
    <div class="row">
        <div class="col-md-12">
            <div class="panel panel-default" style="margin-top: 20px">
                <div class="panel-body">
                    <table id="job-list" class="table table-striped">
                        <thead>
                        <tr>
                            <th>任务名称</th>
                            <th>shell命令</th>
                            <th>cron表达式</th>
                            <th>任务操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        <tr v-for="item in list" v-if="item.name">
                            <td>{item.name}</td>
                            <td>{item.command}</td>
                            <td>{item.cronExpr}</td>
                            <td>
                                <button type="button" class="btn btn-primary btn-sm" @click="edit(item)">编辑</button>
                                <button type="button" class="btn btn-info btn-sm" @click="kill(item)">停止</button>
                                <button type="button" class="btn btn-warning btn-sm" @click="logs(item)">日志</button>
                                <button type="button" class="btn btn-danger btn-sm" @click="del(item)">删除</button>
                            </td>
                        </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>


    <el-dialog
            title="编辑"
            :visible.sync="dialogVisible"
            width="60%"
            :before-close="handleClose">

        <form>
            <div class="form-group">
                <label for="edit-name">任务名称</label>
                <input type="text" class="form-control" v-model="editItem.name" placeholder="任务名称">
            </div>
            <div class="form-group">
                <label for="edit-command">shell命令</label>
                <input type="text" class="form-control" v-model="editItem.command" placeholder="shell命令">
            </div>
            <div class="form-group">
                <label for="edit-cronExpr">cron表达式</label>
                <input type="text" class="form-control" v-model="editItem.cronExpr" placeholder="cron表达式">
            </div>
        </form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save()">确 定</el-button>
        </span>
    </el-dialog>

    <el-dialog
            title="日志"
            :visible.sync="lohShow"
            width="90%"
            :before-close="handleClose">
        <table class="table">
            <tr>
                <td>命令</td>
                <td>错误</td>
                <td>输出</td>
                <td>开始</td>
                <td>结束</td>
                <td>运行</td>
            </tr>
            <tr v-for="item in logList">
                <td>{item.command}</td>
                <td>{item.err}</td>
                <td>{item.output}</td>
                <td>{item.startTime}</td>
                <td>{item.endTime}</td>
                <td>{item.runTime} ms</td>
            </tr>
        </table>
        <el-pagination
                background
                :current-page="currentPage" :page-size="pageSize"
                @current-change="handleCurrentChange"
                layout="prev, pager, next"
                :total="total">
        </el-pagination>

    </el-dialog>


</div>


<script>

    function timeFormat(millsecond) {
        // 前缀补0: 2018-08-07 08:01:03.345
        function paddingNum(num, n) {
            var len = num.toString().length
            while (len < n) {
                num = '0' + num
                len++
            }
            return num
        }

        var date = new Date(millsecond)
        var year = date.getFullYear()
        var month = paddingNum(date.getMonth() + 1, 2)
        var day = paddingNum(date.getDate(), 2)
        var hour = paddingNum(date.getHours(), 2)
        var minute = paddingNum(date.getMinutes(), 2)
        var second = paddingNum(date.getSeconds(), 2)
        var millsecond = paddingNum(date.getMilliseconds(), 3)
        return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second + "." + millsecond
    }

    var DefItem = {name: "", command: "", cronExpr: ""}
    new Vue({
        delimiters: ['{', '}'],
        el: '#vueApp',
        data: {
            editItem: {name: "", command: "", cronExpr: ""},
            list: [],
            dialogVisible: false,
            logList: [],
            lohShow: false,
            total: 0,
            currentPage: 1,
            pageSize: 30,
            showPageItem: {},
            workers: []

        },
        mounted() {
            console.log(this.editItem)
            this.jobList()
            setInterval(this.workerList, 1000 * 5)
        },
        methods: {
            handleClose(done) {
                done();

            },
            handleCurrentChange(page) {
                console.log(page)
                this.currentPage = page
                // this.getList()
                this.logs(this.showPageItem)
            },
            jobList() {

                this.loading = true;
                var data = {}
                this.$http.post("/job/list", data).then(function (res) {
                    if (res.body.Errno == 0) {
                        this.list = res.body.Data
                    }
                }, function () {
                    console.log('请求失败处理');
                });
            },
            del(item) {
                this.$http.post("/job/delete", item).then(function (res) {
                    if (res.body.Errno != 0) {
                        this.$notify({
                            title: res.body.Msg,
                            // message: '',
                            type: 'info'
                        });
                    } else {
                        this.jobList()
                    }
                }, function () {
                    console.log('请求失败处理');
                });
            },
            save() {
                if (this.editItem.name == "" || this.editItem.command == "" || this.editItem.cronExpr == "") {
                    alert("参数错误")
                }
                this.$http.post("/job/save", this.editItem).then(function (res) {
                    if (res.body.Errno != 0) {
                        this.$notify({
                            title: res.body.Msg,
                            // message: '',
                            type: 'info'
                        });
                    } else {
                        this.editItem = DefItem
                        this.dialogVisible = false
                        this.jobList()
                    }
                }, function () {
                    console.log('请求失败处理');
                });
            },
            edit(item) {
                this.dialogVisible = true
                if (item.name) {
                    this.editItem = item
                } else {
                    this.editItem = DefItem
                }

            },
            workerList() {

                this.$http.post("/worker/list").then(function (res) {
                    if (res.body.Errno != 0) {
                        this.$notify({
                            title: res.body.Msg,
                            // message: '',
                            type: 'info'
                        });
                    } else {
                        this.workers = res.body.Data
                    }
                }, function () {
                    console.log('请求失败处理');
                });
            },
            kill(item) {

                this.$http.post("/job/kill", item).then(function (res) {
                    if (res.body.Errno != 0) {
                        this.$notify({
                            title: res.body.Msg,
                            // message: '',
                            type: 'info'
                        });
                    } else {
                        this.jobList()
                    }
                }, function () {
                    console.log('请求失败处理');
                });
            },

            logs(item) {

                if (item.name) {
                    this.showPageItem = item
                }
                var skip = (this.currentPage - 1) * this.pageSize
                skip = skip < 0 ? 0 : skip
                this.$http.post("/job/logs?name=" + this.showPageItem.name + "&limit=" + this.pageSize + "&skip=" + skip).then(function (res) {
                    if (res.body.Errno != 0) {
                        this.$notify({
                            title: res.body.Msg,
                            // message: '',
                            type: 'info'
                        });
                    } else {
                        var data = res.body.Data;
                        this.logList = data.list;
                        for (i = 0; i < this.logList.length; i++) {
                            this.logList[i].runTime = this.logList[i].endTime - this.logList[i].startTime

                            this.logList[i].startTime = timeFormat(this.logList[i].startTime)
                            this.logList[i].endTime = timeFormat(this.logList[i].endTime)
                        }
                        this.lohShow = true
                        this.total = data.count
                        console.log(this.logList)
                    }
                }, function () {
                    console.log('请求失败处理');
                });
            }


        }
    })
</script>
</body>
</html>